package utils

import (
	"bytes"
	"compress/zlib"
	"encoding/base64"
	"encoding/binary"
	"encoding/json"
	"errors"
	"io/ioutil"
	"strings"
)

// FlaskSession python flask session存储格式
type FlaskSession struct {
	Fresh  bool   `json:"_fresh"`
	ID     string `json:"_id"`
	UserID int    `json:"user_id"`
	TS     int    `json:"ts"`
}

// DecodeFlaskSession 解析flaks session
// session分三部分，payload.timestamp.sig
// payload 以.开始的字符串，表示需要zlib解压
// payload base64 url decode (then zlib decode) 转为 FlaskSession对象
// timestamp base64 url decode, then bytes to int 转为 timestamp
func DecodeFlaskSession(session string) (FlaskSession, error) {
	var fs FlaskSession
	var decompress = false
	if session[0] == '.' {
		session = session[1:]
		decompress = true
	}
	var data = strings.Split(session, ".")
	if len(data) != 3 {
		return fs, errors.New("session must contain payload.timestamp.sig,session:" + session)
	}
	var payload, encodeTS, _ = data[0], data[1], data[2]
	var payloadByte, err = base64.RawURLEncoding.DecodeString(payload)
	if err != nil {
		return fs, err
	}
	if decompress {
		var r, err = zlib.NewReader(bytes.NewReader(payloadByte))
		if err != nil {
			return fs, err
		}
		payloadByte, err = ioutil.ReadAll(r)
		if err != nil {
			return fs, err
		}

	}
	// else
	err = json.Unmarshal(payloadByte, &fs)
	if err != nil {
		return fs, err
	}
	// 解析时间戳
	tsByte, err := base64.RawURLEncoding.DecodeString(encodeTS)
	if err != nil {
		return fs, err
	}
	var ts = binary.BigEndian.Uint32(tsByte)
	fs.TS = int(ts)
	return fs, nil

}
